package com.cctc.rds.nrpc.core.client.handler;

import com.cctc.rds.nrpc.core.protocol.message.impl.HeartBeatMessage;
import com.cctc.rds.nrpc.core.util.NrpcLogger;
import com.cctc.rds.nrpc.core.util.PidUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ClientIdleStateHandler extends IdleStateHandler {
    public ClientIdleStateHandler(long timeout) {
        super(0, 0, timeout, TimeUnit.MILLISECONDS);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent) evt;
        switch (event.state()) {
            case READER_IDLE:
            case WRITER_IDLE:
            case ALL_IDLE:
                sendHeartBeat(ctx);
        }
    }

    private void sendHeartBeat(ChannelHandlerContext ctx) {
        HeartBeatMessage heartbeat = HeartBeatMessage.builder().pid(PidUtils.getPid()).build();
        ctx.writeAndFlush(heartbeat);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (cause instanceof IOException) {
            NrpcLogger.getLogger().warn(cause.getMessage());
            return;
        } else {
            super.exceptionCaught(ctx, cause);
        }
    }
}
